/* Utility Functions need by MF code
 * THE GPIO Functions _NEED_ to be checked soon
 *
*/
#include "mfutils.h"
#include "data_types.h"


// Waiting Functions //////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////
// void wait_cycles(Uint32 cycles)
//		spins the processor for (cycles) clock cycles, and then returns
////////////////////////////////////////
void wait_cycles(Uint32 cycles)
{
	volatile Uint32 i; // 32 bits gives a maximum delay of: 4,294,967,296 cycles, or ~42 seconds 
	for(i = 0; i < cycles; i++){};
	return;
}
////////////////////////////////////////
// void wait_usec(Uint32 usec)
//		spins the process for (usec) micro-seconds, and then returns
////////////////////////////////////////
void wait_usec(Uint32 usec)
{
	volatile Uint32 i;
	Uint32 cycles = usec * 10; // still a maximum delay of 4,294,967,296 cycles, or 429,496,729.6 usec
	for(i = 0; i < cycles;i++) {};
	return;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////

// GPIO Functions /////////////////////////////////////////////////////////////////////////////////////
Int16 GPIO_dir( Uint16 whichGPIO, Uint16 dir )
{

    Uint32 bank_id = ( whichGPIO >> 4);
    Uint32 pin_id  = ( 1 << ( whichGPIO & 0xF ) );
    
    if (bank_id == 0)
        if (dir == GPIO_IN)
    	    SYS_GPIO_DIR0 &= ~pin_id;
        else
            SYS_GPIO_DIR0 |= pin_id;

    else if (bank_id == 1)
        if (dir == GPIO_IN)
    	    SYS_GPIO_DIR1 &= ~pin_id;
        else
            SYS_GPIO_DIR1 |= pin_id;

    return 0;
}
Int16 GPIO_set( Uint16 whichGPIO, Uint16 outValue )
{
    Uint32 bank_id = ( whichGPIO >> 4 );
    Uint32 pin_id  = ( 1 << ( whichGPIO & 0xF ) );

    if (bank_id == 0)
        if ((outValue & 1) == 0)
    	    SYS_GPIO_DATAOUT0 &= ~pin_id;
        else
            SYS_GPIO_DATAOUT0 |= pin_id;

    else if (bank_id == 1)
        if ((outValue & 1) == 0)
    	    SYS_GPIO_DATAOUT1 &= ~pin_id;
        else
            SYS_GPIO_DATAOUT1 |= pin_id;

    return 0;
}


Int16 GPIO_get(Uint16 whichGPIO)
{
    Uint16 bank_id = ( whichGPIO >> 4 );
    Uint16 pin_id  = ( whichGPIO & 0xF );
    Int16 value;

    if (bank_id == 0)
        value =  (SYS_GPIO_DATAIN0 >> pin_id) & 1;
    else if (bank_id == 1)
        value = (SYS_GPIO_DATAIN1 >> pin_id) & 1; 
    else
		value = -1; // Returns Error
	return value;

}

///////////////////////////////////////////////////////////////////////////////////////////////////////
